Describe the life cycle of a thread in Java.
Describe the life cycle of a thread in Java.
395
18-Jul-2024
Ravi Vishwakarma
18-Jul-2024In Java, a thread goes through several states during its life cycle. These states represent the different stages a thread can be in from its creation to its termination.
Here is a detailed explanation of the life cycle of a thread in Java:
1. New
NEWNEWstate when it is created but not yet started. At this point, the thread has been instantiated, but thestart()the method has not been called.2. Runnable
RUNNABLERUNNABLEstate when thestart()the method is called. In this state, the thread is ready to run and waiting for CPU time. It is also the state where the thread executes its task. However, due to time-sharing and the thread scheduler, a thread in theRUNNABLEthe state may not be actively running.3. Blocked
BLOCKEDBLOCKEDstate when it attempts to access a synchronized block or method that is currently locked by another thread. The thread remains in this state until the lock is released.Waiting
WAITINGWAITINGstate when it is waiting indefinitely for another thread to perform a particular action. This happens when the thread calls methods likeObject.wait()without a timeout,Thread.join()without a timeout, orLockSupport.park().Timed Waiting
TIMED_WAITINGTIMED_WAITINGstate when it is waiting for a specified period. This can happen when the thread calls methods likeThread.sleep(long millis),Object.wait(long timeout),Thread.join(long millis), orLockSupport.parkNanos(long nanos).Terminated
TERMINATEDTERMINATEDstate when it has finished executing. This can happen either because the thread'srun()the method has been completed, or because an uncaught exception has terminated the thread.Thread Life Cycle Diagram
Summary of Transitions
start()is called.Object.wait(),Thread.join(), orLockSupport.park()is called.Thread.sleep(long),Object.wait(long),Thread.join(long), orLockSupport.parkNanos(long)is called.Object.notify(),Object.notifyAll(), or the corresponding event occurs.run()method completes or an uncaught exception terminates the thread.Read more
Explain the difference between checked and unchecked exceptions. Provide examples.
What are annotations in Java? How are they used?
What is the purpose of the volatile keyword in Java?